package com.cx.base.view.load;



import com.cx.base.view.ILoadManager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LoadingController implements ILoadManager {

    /**
     * 存放所有展示loading 展示的请求
     */
    private HashMap<Disposable, Disposable> mAllRequest;

    /**
     * 目前正在展示loading的请求
     */
    private Set<Disposable> mLoadRequest;

    private ILoad.Loading mLoad;

    private CompositeDisposable mDisposables;


    public LoadingController(ILoad.Loading loading) {
        this.mLoad = loading;
        mAllRequest = new HashMap<>();
        mLoadRequest = new HashSet<>();
        mDisposables = new CompositeDisposable();
    }


    public void add(Disposable add, long delayTime) {
        Disposable subscribe = buildLoadingRequest(add, delayTime);
        mDisposables.add(subscribe);
        mAllRequest.put(add, subscribe);

    }

    private Disposable buildLoadingRequest(final Disposable add, long delayTime) {
        return Observable.timer(delayTime, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) {
                        onLoading();
                        mLoadRequest.add(add);
                    }
                });
    }


    private void onLoading() {
        if (mLoadRequest.size() == 0)
            mLoad.onLoadStart();
    }


    private void dismissLoading() {
        mLoad.onLoadFinish();
    }


    public void remove(Disposable remove) {
        boolean loading = mLoadRequest.contains(remove);
        if (loading) {
            removeRequestFromLoad(remove);
        } else {
            removeRequestFromAll(remove);
        }

    }

    /**
     * 从 目前正在展示loading的请求 移除
     *
     * @param remove key
     */
    private void removeRequestFromLoad(Disposable remove) {
        mLoadRequest.remove(remove);
        if (mLoadRequest.size() == 0)
            dismissLoading();
    }

    /**
     * 从所有请求中移除请求
     *
     * @param remove key
     */
    private void removeRequestFromAll(Disposable remove) {
        Disposable disposable = mAllRequest.get(remove);
        if (disposable != null) {
            mAllRequest.remove(remove);
            disposable.dispose();
        }
    }


    public void onDestroy() {
        mDisposables.dispose();
        mDisposables.clear();
        mAllRequest.clear();
        mLoadRequest.clear();
        mAllRequest = null;
        mLoadRequest = null;
        mLoad = null;
    }

}
